package org.zpmis.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class TokenProcessor {
    //单例模式
    private TokenProcessor(){}
    private static final TokenProcessor myTokenProcessor = new TokenProcessor();
    public static TokenProcessor getInstance()
    {
        return myTokenProcessor;
    }

    public  String generateToken(String sessionId){

        String tokenStr=null;
        String currentTime=null;
        //获取现在系统时间的字符串
        currentTime=System.currentTimeMillis()+"";

        try {
            MessageDigest md=null;
            //使用MD5算法
            md = MessageDigest.getInstance("MD5");
            //把系统时间和sessionId都参与MD5运算
            md.update( currentTime.getBytes());
            md.update( sessionId.getBytes());
            //获取MD5值
            byte tokenByte[]=md.digest();
            //把MD5值转换为16进制字符串
            tokenStr=this.toHex(tokenByte);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return tokenStr;
    }

    private String toHex(byte buffer[]) {
        StringBuffer sb = new StringBuffer();
        String s = null;
        for (int i = 0; i < buffer.length; i++) {
            s = Integer.toHexString((int) buffer[i] & 0xff);
            if (s.length() < 2) {
                sb.append('0');
            }
            sb.append(s);
        }
        return sb.toString();
    }

    public static void main(String[]args){
    // 生成Token
    String phoneNumberId = "loginToken_" + "8613426000210";
    String newToken = TokenProcessor.getInstance().generateToken(phoneNumberId);
    log.info("token:"+newToken);
        String encode = DigestUtils.md5DigestAsHex("123456".getBytes());
        log.info("encode:"+encode);
    }
}
